package uk.co.cocking.getinline2.pipeline.transformers;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;
import uk.co.cocking.getinline2.exceptions.Defect;
import uk.co.cocking.getinline2.exceptions.EnvironmentException;
import uk.co.cocking.getinline2.record.Record;

public class XmlFormatter extends AbstractTransformer<Record, String> {
	
	private Element root;

	@Override
	public List<String> close() throws EnvironmentException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		Serializer serializer;
		try {
			serializer = new Serializer(out, "UTF-8");
			serializer.setIndent(4);
			serializer.write(new Document(root));
		} catch (UnsupportedEncodingException e) {
			throw new Defect("cannot encode to UTF-8", e);
		} catch (IOException e) {
			throw new EnvironmentException("could not write to serializer", e);
		}
		return enlist(out.toString());
	}

	@Override
	public List<String> open() {
		root = new Element("document");
		return emptyList();
	}

	@Override
	public List<String> transform(Record item) {
		Element row = new Element("row");
		root.appendChild(row);
		for (String fieldName: item.fieldNames()) {
			Element cell = new Element(fieldName);
			cell.appendChild(item.getString(fieldName));
			row.appendChild(cell);
		}
		return emptyList();
	}

}
